<template>
  <div class="container">
    <el-row :gutter="20">
        <el-button-group :class="{ 'hasFix': needFix }" style="margin-bottom: 10px;z-index: 999">
          <el-button type="primary" @click="onSave(dialogForm)">保 存</el-button>
          <el-button type="primary" @click="csOpen=true">参数说明</el-button>
          <el-button @click="goBack">返 回</el-button>
        </el-button-group>
        <el-form
            ref="dialogForm"
            :rules="formRules"
            :model="formData"
            size="small"
            label-position="top"
        >
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="groupId" label="组名称">
                <el-select
                    v-model="formData.groupId"
                    placeholder="选择模板所在组"
                >
                  <el-option
                      v-for="item in groupData"
                      :key="item.id"
                      :label="item.groupName"
                      :value="item.id"
                  >
                    {{ item.groupName }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="name" label="模板名称">
                <el-input v-model="formData.name"  maxlength="64"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="folder" label="文件目录">
                <el-input v-model="formData.folder" placeholder="为空则是模板名"  maxlength="64"/>
              </el-form-item>
            </el-col>
              <el-col :span="6">
                <el-form-item prop="fileName" label="文件名称">
                  <el-input v-model="formData.fileName" placeholder="可使用velocity变量" 
                            maxlength="100"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="content" label="模板内容">
<!--                  <div style="display: inline-block;margin-bottom: 5px;">-->
<!--                    <el-link type="primary" :underline="false"-->
<!--                             href="https://www.cnblogs.com/codingsilence/archive/2011/03/29/2146580.html"-->
<!--                             target="_blank">Velocity语法-->
<!--                    </el-link>-->
<!--                    <span class="split">|</span>-->
<!--                    <el-dropdown @command="changeCodeTheme">-->
<!--                <span class="el-dropdown-link">-->
<!--                  代码样式<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                </span>-->
<!--                      <el-dropdown-menu slot="dropdown">-->
<!--                        <el-dropdown-item v-for="item in codeThemeList" :command="item">{{ item }}</el-dropdown-item>-->
<!--                      </el-dropdown-menu>-->
<!--                    </el-dropdown>-->
<!--                    <span class="split">|</span>-->
<!--                    快捷键：-->
<!--                    <el-tag v-for="item in shortcutKeyList" effect="plain" size="small" style="margin-right: 5px">-->
<!--                      {{ item }}-->
<!--                    </el-tag>-->
<!--                  </div>-->
                  <div id="editor">
                  <Codemirror
                      class="code"
                      v-model="formData.content"
                      :style="{ height: '100%' }"
                      :extensions="extensions"
                      :autofocus="true"
                      :disabled="false"

                  />
                  </div>
                </el-form-item>
              </el-col>
          </el-row>
        </el-form>
      <el-drawer title="参数说明"  v-model="csOpen" size="30%" :show-close="false">
        <div :class="{ 'hasFix': needFix }" style="font-size: 14px;">
          <h4 style="margin: 5px 0">
            Velocity变量
            <span class="velocity-tip">
              点击变量直接插入
            </span>
          </h4>
          <el-tabs v-model="activeName" @tab-click="onTabClick">
            <el-tab-pane v-for="item in velocityConfig" :key="item.name" :label="item.label" :name="item.name"
                         :content="item"/>
          </el-tabs>
          <div class="velocity-var">
            <el-tree
                :data="treeData"
                :props="defaultProps"
                :indent="4"
                accordion
            >
              <template #default="{ node, data }">
                <span v-if="data.children && data.children.length > 0">{{ data.expression }}</span>
                <span v-else>
                  <a @click="onExpressionClick(data.expression)">{{ data.expression }}</a>：{{ data.text }}
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </el-drawer>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {Codemirror} from 'vue-codemirror'
import {saveorUpadateDate} from "@/api/index";
import {javascript} from "@codemirror/lang-javascript";
import {oneDark} from "@codemirror/theme-one-dark";
import {ElMessage, FormInstance} from "element-plus";
import axios from "axios";
import {ref, reactive, onMounted, watch} from "vue";
import {useRoute, useRouter} from "vue-router";

let TEMPLATE_CODE_THEME = 'gen.template.code.theme'
let csOpen=ref(false)
let groupData = ref([])
let codeThemeList = ref(['neat', 'darcula', 'material'])
let extensions = [javascript(), oneDark]
let route = useRoute()
let router=useRouter()
let shortcutKeyList = ref([
  '保存(Ctrl+S)',
  '删除当行(Ctrl+D)',
  '复制当行(Ctrl+C)',
  '剪切当行(Ctrl+X)',
  '替换(Ctrl+Shift+F)'
])
let formData = ref({
      id: 0,
      groupId: '',
      groupName: '',
      name: '',
      folder: '',
      fileName: '',
      content: ''
    }
)
let formRules = reactive({
      groupId: [
        {required: true, message: '不能为空', trigger: 'blur'}
      ],
      name: [
        {required: true, message: '不能为空', trigger: 'blur'}
      ],
      fileName: [
        {required: true, message: '不能为空', trigger: 'blur'}
      ],
      content: [
        {required: true, message: '不能为空', trigger: 'blur'}
      ]
    }
)
let isVelocityBarFixed = ref(false)
let activeName = ref("java")
let collapseActiveName = ref("0")
let treeData = ref([])
let velocityConfig = ref([])
let defaultProps = {
  children: 'children',
  label: 'expression'
}
let needFix = ref(false)
let keywordHelpShow = ref(false)
let dialogForm = ref(null)
watch(() => route.path, (newPath, oldPath) => {
  if (route.query.id && route.query.groupId) {
    reload();
  }
});
onMounted(() => {
  reload()
  window.addEventListener('scroll', handlerScroll)
  watchKeydown()
})

const watchKeydown = () => {
  document.onkeydown = function (e) {
    let key = window.event.keyCode;
    if (key == 83 && event.ctrlKey) {//s == 83 && event.ctrlKey
      window.event.preventDefault() //关闭浏览器快捷键
      onSave(dialogForm);
    }
    if (event.ctrlKey && key == 82) {
      window.event.preventDefault() //关闭浏览器快捷键
    }

  };
}
const goBack = () => {
     router.push("/admin/tool/generate/template")
}
const onSave = (form: FormInstance) => {
  form.validate((valid) => {
    if (valid) {
      const opt = formData.value.id ? 'update' : 'add'
      const uri = `/process/generator/templateconfig/save`
      saveorUpadateDate(uri, formData.value).then(resp => {
        if (opt === 'add') {
          formData.value.id = resp.id
        }
        ElMessage.success('保存成功')
      })
    }
  })
}
const reload = () => {
  const id = route.query.id || 0
  if (id > 0) {
    saveorUpadateDate(`/process/generator/templateconfig/get/${id}`, {}).then((resp) => {
      formData.value = resp
    })
  }
  loadVelocityVar()
  loadGroups(route.query.groupId)

}
const loadVelocityVar = () => {
  axios.get(`/velocity/java.json?q=${new Date().getTime()}`).then(content => {
    debugger
    velocityConfig.value.push({
      name: 'java',
      label: 'Java变量',
      data: content.data
    })
    treeData.value = content.data.data
  })
  axios.get(`/velocity/csharp.json?q=${new Date().getTime()}`).then(content => {
    debugger
    velocityConfig.value.push({
      name: 'csharp',
      label: 'C#变量',
      data: content.data
    })
  })
}
const loadGroups = (groupId: any) => {
  saveorUpadateDate(`/process/generator/templategroup/list/`, {}).then((resp) => {
    groupData.value = resp
    if (!groupId && groupData.value.length > 0) {
      groupId = groupData.value[0].id
    }
    if (groupId) {
      formData.value.groupId = parseInt(groupId);
    }
  })
}
const handlerScroll = () => {
  const scrollTop = window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop
  needFix.value = scrollTop > 80
}
const onExpressionClick = (exp) => {
  // const codemirror = this.$refs.editor.codemirror
  // // 插入表达式
  // codemirror.replaceSelection(exp)
  // // 重新获得光标
  // codemirror.focus()
}
const handleNodeClick = (node: any) => {
  console.log(node)
}
const onTabClick = (tab: any) => {
  debugger
  const item = velocityConfig.value[tab.index]
  treeData.value = item.data.data
}
const changeCodeTheme = (theme: any) => {
  localStorage.setItem(TEMPLATE_CODE_THEME, theme)
}

</script>
<style lang="scss" scoped>
::v-deep .code {
  width: 100%;
  height: 100%;
  overflow: hidden;
::-webkit-scrollbar {
  outline: none;
  width: 12px;
  height: 12px;
  background-color: transparent;
  //@include setTransition(all, 0.3s, ease);
  transition: all 0.3 ease;
  -moz-transition:all 0.3 ease;
  -webkit-transition: all 0.3 ease;
}
::-webkit-scrollbar-track {
  background-color: rgba(30, 30, 30, 0);
}
::-webkit-scrollbar-thumb {
  background-color: rgba(80, 80, 80, 0.3);
}
::-webkit-scrollbar-thumb:hover {
  outline: none;
  background-color: rgba(80, 80, 80, 0.7);
}
.CodeMirror {
  height: calc(100vh - 91px) !important;
  resize: none;
  outline: none;
  border: none;
  font-family: inherit;
  font-size: inherit;
}
.CodeMirror-scroll {
  height: 100%;
  overflow-y: hidden;
}
}
::v-deep .md-active {
.CodeMirror {
  height: calc(100vh - 121px) !important;
}
}
#editor {
  width: 100%;
  height: calc(100% - 30px);
}
</style>
